/*
 *所有关于Quality_InboundTest类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*Quality_InboundTestService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using iMES.Core.BaseProvider;
using iMES.Core.Enums;
using iMES.Core.Extensions;
using iMES.Core.Extensions.AutofacManager;
using iMES.Core.Utilities;
using iMES.Custom.IRepositories;
using iMES.Entity.DomainModels;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Threading.Tasks;
using Yun.New_QualityTest.IRepositories;
using Yun.New_QualityTest.Repositories;
using YUN.LReport.IRepositories;
using YUN.LReport.Repositories;
using ZJY.Purchase.IRepositroies;
using ZJY.Purchase.Repositroies;

namespace Yun.New_QualityTest.Services
{
    public partial class Quality_InboundTestService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IQuality_InboundTestRepository _repository;//访问数据库
        private readonly IBase_NumberRuleRepository _numberRuleRepository;

        private readonly IPurchase_OrderRepository _purchaseOrderRepository;  //采购订单
        private readonly IPurchase_supplierRepository _purchaseOrderSupplierRepository;  //采购订单供应商
        private readonly IPurchase_employeeRepository _purchaseEmployeeRepository;  //采购人员
        private readonly IMaterialMasterRepository _bomMasterRepository;  //物品BOM
        private readonly IInspectionDetailRepository _inspectionDetailRepository;  //检验单明细; 
        private readonly IAttachmentRepository _attachmentRepository;



        [ActivatorUtilitiesConstructor]
        public Quality_InboundTestService(
            IQuality_InboundTestRepository dbRepository,
            IBase_NumberRuleRepository numberRuleRepository,
                IPurchase_OrderRepository purchaseOrderRepository,
                IPurchase_supplierRepository purchaseOrderSupplierRepository,
                IPurchase_employeeRepository purchaseEmployeeRepository,
                    IMaterialMasterRepository bomMasterRepository,
                    IInspectionDetailRepository inspectionDetailRepository,
            IHttpContextAccessor httpContextAccessor,
            IAttachmentRepository attachmentRepository
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _purchaseOrderRepository = purchaseOrderRepository;
            _purchaseOrderSupplierRepository = purchaseOrderSupplierRepository;
            _purchaseEmployeeRepository = purchaseEmployeeRepository;
            _bomMasterRepository = bomMasterRepository;
            _numberRuleRepository = numberRuleRepository;
            _inspectionDetailRepository = inspectionDetailRepository;
            _attachmentRepository = attachmentRepository;

            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }


        WebResponseContent webResponse = new WebResponseContent();


        /// <summary>
        /// 获取table1的数据
        /// </summary>
        /// <param name="loadData"></param>
        /// <returns></returns>
        public async Task<object> GetTable1Data(PageDataOptions loadData)
        {
            //Equip_SpotMaintPlanModelBody.vue中loadTableBefore方法查询前给loadData.Value写入的值
            List<where> list = loadData.Wheres.DeserializeObject<List<where>>();
            //获取查询到的总和数
            int total = await MaterialMasterRepository.Instance.FindAsIQueryable(x => x.MaterialId == new Guid(list[0].value)).CountAsync();

            var data = await MaterialMasterRepository.Instance
                //这里可以自己查询条件，从 loadData.Value找前台自定义传的查询条件
                .FindAsIQueryable(x => x.MaterialId == new Guid(list[0].value))
                //分页
                .TakeOrderByPage(1, 10, x => new Dictionary<object, QueryOrderBy>() { { x.CreateDate, QueryOrderBy.Desc } })
                .Select(s => new
                {
                    s.MaterialId,
                    s.MaterialName,
                    s.MaterialCode,
                    s.MaterialType,
                    s.MaterialModel,
                    s.UnitName,
                    s.Brand,
                    s.PurchaseUnitPrice,
                    s.SalePrice,
                    s.PurchaseUnitQuantity,


                })
                .ToListAsync();
            object gridData = new { rows = data, total };
            return gridData;



        }
        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="saveDataModel"></param>
        /// <returns></returns>
        public override WebResponseContent Add(SaveModel saveDataModel)
        {

            // 添加空值检查
            TableExtra tableExtra = null;
            try
            {
                tableExtra = saveDataModel.Extra.ToString().DeserializeObject<TableExtra>();
                // 清空DetailData，防止基类处理
              
            }
            catch (Exception ex)
            {
                Console.WriteLine($"反序列化TableExtra失败: {ex.Message}");
                return webResponse.Error("明细数据格式错误，请检查提交的数据。");
            }

            // 检查表格列表为空
            if (tableExtra == null || tableExtra.Table1List == null || !tableExtra.Table1List.Any())
            {
                Console.WriteLine("表格明细数据为空");
                // 如果没有明细数据，可以选择返回错误信息或继续处理主表数据
                // return webResponse.Error("请添加至少一条明细数据");
            }
            // 添加空值检查
            //TableExtra tableExtra = saveDataModel.Extra.ToString().DeserializeObject<TableExtra>();

            // 保存附件信息到临时变量，稍后在事务中使用
            string attachmentPath = null;
            string attachmentName = "附件";
            string attachmentSize = "未知大小";
            bool hasAttachment = false;

            if (saveDataModel.MainData.ContainsKey("AttachmentPath") &&
                !string.IsNullOrEmpty(saveDataModel.MainData["AttachmentPath"].ToString()))
            {
                hasAttachment = true;
                attachmentPath = saveDataModel.MainData["AttachmentPath"].ToString();
                if (saveDataModel.MainData.ContainsKey("AttachmentName"))
                    attachmentName = saveDataModel.MainData["AttachmentName"].ToString();
                if (saveDataModel.MainData.ContainsKey("AttachmentSize"))
                    attachmentSize = saveDataModel.MainData["AttachmentSize"].ToString();
            }

            // 保存到数据库前
            AddOnExecuting = (Quality_InboundTest quality_InboundTest, object obj) =>
            {
                if (string.IsNullOrWhiteSpace(quality_InboundTest.InspectionOrderCode))
                    quality_InboundTest.InspectionOrderCode = GetToolCode();

                if (repository.Exists(x => x.InspectionOrderCode == quality_InboundTest.InspectionOrderCode))
                {
                    return webResponse.Error("该订单号已存在，请重新输入！");
                }
                return WebResponseContent.Instance.OK();
            };

            // 保存到数据库后，此处已经提交了数据库，处于事务中
            AddOnExecuted = (Quality_InboundTest quality_InboundTest, object obj) =>
            {
                try
                {
                    // 1. 处理明细表数据
                    List<InspectionDetail> newsList = tableExtra.Table1List.Select(s => new InspectionDetail
                    {
                        InspectionDetailID = Guid.NewGuid(),
                        InspectionOrderID = quality_InboundTest.InspectionOrderID,
                        MaterialId = s.MaterialId,
                        MaterialCode = s.MaterialCode ?? "",
                        MaterialName = s.MaterialName,
                        MaterialType = s.MaterialType,
                        MaterialModel = s.MaterialModel,
                        UnitName = s.UnitName,
                        Brand = s.Brand,
                        PurchaseUnitPrice = s.PurchaseUnitPrice,
                        SalePrice = s.SalePrice,
                        ReturnQuantity = s.ReturnQuantity,
                        StockableQuantity = s.StockableQuantity,
                        QualifiedQuantity = s.QualifiedQuantity,
                        InspectionDetailRemark = s.InspectionDetailRemark,
                        InspectedQuantity = s.InspectedQuantity,
                        InspectionType = s.InspectionType ?? "",
                        ReceivedQuantity = s.ReceivedQuantity,
                    }).ToList();

                    // 设置默认创建人信息
                    newsList.ForEach(x => { x.SetCreateDefaultVal(); });

                    // 新增明细表数据
                    repository.AddRange(newsList);

                    // 2. 处理附件表数据 - 在同一事务中添加附件
                    if (hasAttachment && !string.IsNullOrEmpty(attachmentPath))
                    {
                        var attachment = new Attachment
                        {
                            AttachmentID = Guid.NewGuid(),
                            InspectionOrderID = quality_InboundTest.InspectionOrderID, // 此时主键已生成
                            AttachmentFileName = attachmentName,
                            AttachmentFileSize = attachmentSize,
                            AttachmentFilePath = attachmentPath,
                            UploadDate = DateTime.Now
                        };

                        // 设置创建信息
                        attachment.SetCreateDefaultVal();

                        // 保存到附件表
                        _attachmentRepository.Add(attachment);
                    }

                    // 最终保存所有更改
                    repository.SaveChanges();
                    return WebResponseContent.Instance.OK();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"保存数据时发生错误: {ex.Message}");
                    return webResponse.Error($"保存数据时发生错误: {ex.Message}");
                }
            };

            return base.Add(saveDataModel);
        }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="file">上传的文件</param>
        /// <returns>文件保存路径</returns>
        public async Task<WebResponseContent> UploadFile(IFormFile file)
        {
            WebResponseContent responseContent = new WebResponseContent();

            try
            {
                if (file == null || file.Length == 0)
                {
                    return responseContent.Error("未检测到上传的文件");
                }

                // 检查文件大小限制（例如：50MB）
                if (file.Length > 52428800)
                {
                    return responseContent.Error("文件大小超过限制，最大允许50MB");
                }

                // 获取文件扩展名
                string fileExt = System.IO.Path.GetExtension(file.FileName).ToLowerInvariant();

                // 检查文件类型（可根据需要限制文件类型）
                string[] allowedExts = { ".jpg", ".jpeg", ".png", ".gif", ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".zip", ".rar" };
                if (!allowedExts.Contains(fileExt))
                {
                    return responseContent.Error("不支持的文件类型");
                }

                // 生成新的文件名，避免文件名冲突
                string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Guid.NewGuid().ToString("N") + fileExt;

                // 设置保存路径（相对路径，方便前端访问）
                string relativePath = $"/Upload/InboundTest/{DateTime.Now.ToString("yyyy-MM")}/";

                // 获取物理路径
                string uploadPath = System.IO.Path.Combine(AppContext.BaseDirectory, "wwwroot", relativePath.TrimStart('/'));

                // 确保目录存在
                if (!System.IO.Directory.Exists(uploadPath))
                {
                    System.IO.Directory.CreateDirectory(uploadPath);
                }

                // 完整的物理文件路径
                string filePath = System.IO.Path.Combine(uploadPath, newFileName);

                // 保存文件
                using (var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 返回相对路径，前端可以通过此路径访问文件
                string returnPath = relativePath + newFileName;

                return responseContent.OK(null, returnPath);
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"文件上传异常: {ex.Message}");
                return responseContent.Error("文件上传失败：" + ex.Message);
            }
        }
        /// <summary>
        /// 自动生成设备编号
        /// </summary>
        /// <returns></returns>
        public string GetToolCode()
        {
            DateTime dateNow = (DateTime)DateTime.Now.ToString("yyyy-MM-dd").GetDateTime();
            //查询当天最新的订单号
            string defectItemCode = repository.FindAsIQueryable(x => x.CreateDate > dateNow && x.InspectionOrderCode.Length > 8)
                .OrderByDescending(x => x.InspectionOrderCode)
                .Select(s => s.InspectionOrderCode)
                .FirstOrDefault();
            Base_NumberRule numberRule = _numberRuleRepository.FindAsIQueryable(x => x.FormCode == "Quality_InboundTest")
                .OrderByDescending(x => x.CreateDate)
                .FirstOrDefault();
            if (numberRule != null)
            {
                string rule = numberRule.Prefix + DateTime.Now.ToString(numberRule.SubmitTime.Replace("hh", "HH"));
                if (string.IsNullOrEmpty(defectItemCode))
                {
                    rule += "1".PadLeft(numberRule.SerialNumber, '0');
                }
                else
                {
                    rule += (defectItemCode.Substring(defectItemCode.Length - numberRule.SerialNumber).GetInt() + 1).ToString("0".PadLeft(numberRule.SerialNumber, '0'));
                }
                return rule;
            }
            else //如果自定义序号配置项不存在，则使用日期生成
            {
                return DateTime.Now.ToString("yyyyMMddHHmmssffff");
            }
        }
        //到货检验明细表
        public class Table1
        {

            /// <summary>
            ///到货检验明细表Id
            /// </summary>
            [Key]
            [Display(Name = "到货检验明细表Id")]
            [Column(TypeName = "uniqueidentifier")]
            public Guid InspectionDetailID { get; set; }



            /// <summary>
            ///备注
            /// </summary>
            [Display(Name = "备注")]
            [MaxLength(200)]
            [Column(TypeName = "varchar(200)")]
            public string? InspectionDetailRemark { get; set; }

            /// <summary>
            ///退货数量
            /// </summary>
            [Display(Name = "退货数量")]
            [Column(TypeName = "int")]
            public int? ReturnQuantity { get; set; }

            /// <summary>
            ///可入库数量
            /// </summary>
            [Display(Name = "可入库数量")]
            [Column(TypeName = "int")]
            public int? StockableQuantity { get; set; }

            /// <summary>
            ///合格数量
            /// </summary>
            [Display(Name = "合格数量")]
            [Column(TypeName = "int")]
            public int? QualifiedQuantity { get; set; }



            /// <summary>
            ///检验数量
            /// </summary>
            [Display(Name = "检验数量")]
            [Column(TypeName = "int")]
            public int? InspectedQuantity { get; set; }

            /// <summary>
            ///检验类型
            /// </summary>
            [Display(Name = "检验类型")]
            [MaxLength(10)]
            [Column(TypeName = "varchar(10)")]
            public string? InspectionType { get; set; }

            /// <summary>
            ///到货检验单外键Id
            /// </summary>
            [Display(Name = "到货检验单外键Id")]
            [Column(TypeName = "uniqueidentifier")]
            public Guid InspectionOrderID { get; set; }

            /// <summary>
            ///收货数量
            /// </summary>
            [Display(Name = "收货数量")]
            [Column(TypeName = "int")]
            public int? ReceivedQuantity { get; set; }



            /// <summary>
            ///
            /// </summary>
            [Display(Name = "MaterialId")]
            [Column(TypeName = "uniqueidentifier")]
            public Guid? MaterialId { get; set; }

            /// <summary>
            ///物料编码
            /// </summary>
            [Display(Name = "物料编码")]
            [MaxLength(50)]
            [Column(TypeName = "varchar(50)")]
            public string? MaterialCode { get; set; }

            /// <summary>
            ///物料名称
            /// </summary>
            [Display(Name = "物料名称")]
            [MaxLength(100)]
            [Column(TypeName = "varchar(100)")]
            public string? MaterialName { get; set; }

            /// <summary>
            ///物料类型
            /// </summary>
            [Display(Name = "物料类型")]
            [MaxLength(50)]
            [Column(TypeName = "varchar(50)")]
            public string? MaterialType { get; set; }

            /// <summary>
            ///规格型号
            /// </summary>
            [Display(Name = "规格型号")]
            [MaxLength(100)]
            [Column(TypeName = "varchar(100)")]
            public string? MaterialModel { get; set; }

            /// <summary>
            ///默认单位名称
            /// </summary>
            [Display(Name = "默认单位名称")]
            [MaxLength(50)]
            [Column(TypeName = "varchar(50)")]
            public string? UnitName { get; set; }

            /// <summary>
            ///品牌
            /// </summary>
            [Display(Name = "品牌")]
            [MaxLength(100)]
            [Column(TypeName = "varchar(100)")]
            public string? Brand { get; set; }

            /// <summary>
            ///采购单价
            /// </summary>
            [Display(Name = "采购单价")]
            [DisplayFormat(DataFormatString = "10,2")]
            [Column(TypeName = "decimal")]
            public decimal? PurchaseUnitPrice { get; set; }

            /// <summary>
            ///销售单价
            /// </summary>
            [Display(Name = "销售单价")]
            [DisplayFormat(DataFormatString = "10,2")]
            [Column(TypeName = "decimal")]
            public decimal? SalePrice { get; set; }
        }

        public class TableExtra
        {
            /// <summary>
            /// 从表1
            /// </summary>
            public List<Table1> Table1List { get; set; }


        }
        public class where
        {
            public string name { get; set; }
            public string value { get; set; }
        }

        /// <summary>
        /// 查询参数类
        /// </summary>
        public class SearchParameters
        {
            /// <summary>
            /// 参数名
            /// </summary>
            public string Name { get; set; }

            /// <summary>
            /// 参数值
            /// </summary>
            public string Value { get; set; }
        }

        /// <summary>
        /// 获取包含供应商、采购员等关联信息的采购单列表
        /// </summary>
        /// <param name="options">分页参数</param>
        /// <returns>采购单及关联信息</returns>
        public async Task<object> GetPurchaseOrderWithDetails(PageDataOptions options)
        {
            // 获取分页信息并确保值有效
            int pageIndex = options.Page <= 0 ? 1 : options.Page;
            int pageSize = options.Rows <= 0 ? 30 : options.Rows;  // 默认每页30条记录

            // 解析查询条件 - 使用已有的where类而不是SearchParameters
            List<where> whereList = new List<where>();
            try
            {
                if (options.Wheres != null && !string.IsNullOrEmpty(options.Wheres))
                {
                    whereList = options.Wheres.DeserializeObject<List<where>>();
                }
            }
            catch (Exception ex)
            {
                // 记录异常信息，但不影响继续执行
                Console.WriteLine($"解析查询条件异常: {ex.Message}");
            }

            // 构建基础查询
            var query = _purchaseOrderRepository.FindAsIQueryable(x => true);

            // 应用查询条件
            if (whereList != null && whereList.Count > 0)
            {
                foreach (var param in whereList)
                {
                    if (!string.IsNullOrEmpty(param.value))
                    {
                        switch (param.name.ToLower())
                        {
                            case "order_no":
                                query = query.Where(x => x.order_no.Contains(param.value));
                                break;
                            case "order_title":
                                query = query.Where(x => x.order_title.Contains(param.value));
                                break;
                            case "purchase_date":
                                if (DateTime.TryParse(param.value, out DateTime date))
                                {
                                    query = query.Where(x => x.purchase_date == date);
                                }
                                break;
                            case "status":
                                query = query.Where(x => x.status == param.value);
                                break;
                            default:
                                break;
                        }
                    }
                }
            }

            // 获取总记录数
            int total = await query.CountAsync();

            // 获取采购单列表（与供应商表连接）
            var purchaseOrders = await query
                // 分页和排序
                .TakeOrderByPage(pageIndex, pageSize, x => new Dictionary<object, QueryOrderBy>()
                {
                    { x.purchase_date, QueryOrderBy.Desc }
                })
                // 连接供应商表
                .Join(_purchaseOrderSupplierRepository.FindAsIQueryable(x => true),
                    order => order.purchase_supplierid,
                    supplier => supplier.purchase_supplierid,
                    (order, supplier) => new
                    {
                        // 采购单信息
                        PurchaseOrderId = order.purchase_orderid,
                        OrderNo = order.order_no,
                        OrderTitle = order.order_title,
                        SalesNo = order.sales_no,
                        PurchaseDate = order.purchase_date,
                        RelatedProject = order.related_project,
                        Status = order.status,



                        // 供应商信息
                        SupplierId = supplier.purchase_supplierid,
                        SupplierName = supplier.supplier_name,
                        ContactPerson = supplier.contact_person,
                        ContactPhone = supplier.contact_phone,

                        // 采购员ID
                        PurchaseEmployeeId = order.purchase_employeeid
                    })
                .ToListAsync();

            // 获取采购人员ID列表
            var employeeIds = purchaseOrders.Select(x => x.PurchaseEmployeeId).Distinct().ToList();

            // 查询对应的采购人员信息
            var employeeDict = await _purchaseEmployeeRepository
                .FindAsIQueryable(x => employeeIds.Contains(x.purchase_employeeid))
                .Select(e => new
                {
                    EmployeeId = e.purchase_employeeid,
                    PurchasePerson = e.purchase_person,
                    PurchaseDept = e.purchase_dept,
                    ContactMethod = e.contact_method
                })
                .ToDictionaryAsync(k => k.EmployeeId, v => v);

            // 将采购人员信息添加到结果中
            var result = purchaseOrders.Select(po =>
            {
                // 尝试获取采购人员信息
                var hasEmployee = employeeDict.TryGetValue(po.PurchaseEmployeeId, out var employee);

                return new
                {
                    po.PurchaseOrderId,
                    po.OrderNo,
                    po.OrderTitle,
                    po.SalesNo,
                    po.PurchaseDate,
                    po.RelatedProject,
                    po.Status,

                    po.SupplierId,
                    po.SupplierName,
                    po.ContactPerson,
                    po.ContactPhone,

                    po.PurchaseEmployeeId,
                    // 如果找到采购人员信息则使用，否则使用默认值
                    PurchasePerson = hasEmployee ? employee.PurchasePerson : string.Empty,
                    PurchaseDept = hasEmployee ? employee.PurchaseDept : string.Empty,
                    ContactMethod = hasEmployee ? employee.ContactMethod : string.Empty
                };
            }).ToList();

            // 组织返回结果
            object gridData = new { rows = result, total };
            return gridData;
        }

        //public override PageGridData<Quality_InboundTest> GetPageData(PageDataOptions options)
        //{

        //    if (options.Page <= 0) options.Page = 1; // 设置默认页码为1
        //    if (options.Rows <= 0) options.Rows = 10; // 设置一个默认的页大小

        //    //创建一个匿名类型来包含所有需要的字段
        //    var query = from inbound in repository.DbContext.Set<Quality_InboundTest>()
        //                join order in _purchaseOrderRepository.DbContext.Set<Purchase_Order>()
        //                on inbound.PurchaseOrderID equals order.purchase_orderid
        //                join detail in _inspectionDetailRepository.DbContext.Set<InspectionDetail>()
        //                on inbound.InspectionOrderID equals detail.InspectionOrderID
        //                select new
        //                {
        //                    inbound.InspectionOrderID,
        //                    inbound.InspectionOrderCode,
        //                    inbound.InspectionSubject,
        //                    inbound.InspectionDate,
        //                    inbound.Inspector,
        //                    inbound.Department,
        //                    inbound.ContactPhone,
        //                    inbound.PurchaseOrderID,
        //                    order.order_no,
        //                    inbound.CreateDate,
        //                    inbound.Creator,
        //                    detail.InspectionDetailID,
        //                    detail.InspectionDetailRemark,
        //                    detail.ReturnQuantity,
        //                    detail.StockableQuantity,
        //                    detail.QualifiedQuantity,
        //                    detail.InspectedQuantity,
        //                    detail.InspectionType,
        //                    detail.ReceivedQuantity,
        //                    detail.MaterialId,
        //                    detail.MaterialCode,
        //                    detail.MaterialName,
        //                    detail.MaterialType,
        //                    detail.MaterialModel,
        //                    detail.UnitName,
        //                    detail.Brand,
        //                    detail.PurchaseUnitPrice,
        //                    detail.SalePrice

        //                };

        //    int total = query.Count();
        //    var data = query.Skip((options.Page - 1) * options.Rows).Take(options.Rows).ToList()
        //          .Select(x => new Quality_InboundTest
        //          {
        //              InspectionOrderID = x.InspectionOrderID,
        //              InspectionOrderCode = x.InspectionOrderCode,
        //              InspectionSubject = x.InspectionSubject,
        //              InspectionDate = x.InspectionDate,
        //              Inspector = x.Inspector,
        //              Department = x.Department,
        //              ContactPhone = x.ContactPhone,
        //              PurchaseOrderID = x.PurchaseOrderID,
        //              InspectionDetailID = x.InspectionDetailID,
        //              InspectionDetailRemark = x.InspectionDetailRemark,
        //              ReturnQuantity = x.ReturnQuantity,
        //              StockableQuantity = x.StockableQuantity,
        //              QualifiedQuantity = x.QualifiedQuantity,
        //              InspectedQuantity = x.InspectedQuantity,
        //              InspectionType = x.InspectionType,
        //              ReceivedQuantity = x.ReceivedQuantity,
        //              MaterialId = x.MaterialId ?? Guid.Empty,
        //              MaterialCode = x.MaterialCode,
        //              MaterialName = x.MaterialName,
        //              MaterialType = x.MaterialType,
        //              MaterialModel = x.MaterialModel,
        //              UnitName = x.UnitName,
        //              Brand = x.Brand,
        //              PurchaseUnitPrice = x.PurchaseUnitPrice ?? 0m,
        //              SalePrice = x.SalePrice ?? 0m,
        //              order_no = x.order_no,
        //          }).ToList();


        //    return new PageGridData<Quality_InboundTest>()
        //    {
        //        rows =data,

        //        total = total,

        //    };

        //}
        /// <summary>
        /// 获取到货检验表与采购订单表的联合查询结果（LINQ查询语法版本）
        /// </summary>
        /// <param name="options">分页参数</param>
        /// <returns>包含采购单信息的到货检验信息</returns>
        public async Task<object> GetInboundTestWithPurchaseOrderLinq(PageDataOptions options)
        {
            try
            {
                // 获取分页信息
                int pageSize = options.Rows > 0 ? options.Rows : 10;
                int pageIndex = options.Page > 0 ? options.Page : 1;

                // 解析查询条件
                List<where> whereList = new List<where>();
                try
                {
                    if (options.Wheres != null && !string.IsNullOrEmpty(options.Wheres))
                    {
                        whereList = options.Wheres.DeserializeObject<List<where>>();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"解析查询条件异常: {ex.Message}");
                }

                // 构建基本查询
                var inboundQuery = repository.FindAsIQueryable(x => true);

                // 应用查询条件
                if (whereList != null && whereList.Count > 0)
                {
                    foreach (var param in whereList)
                    {
                        if (!string.IsNullOrEmpty(param.value))
                        {
                            switch (param.name.ToLower())
                            {
                                case "inspectionordercode":
                                    inboundQuery = inboundQuery.Where(x => x.InspectionOrderCode.Contains(param.value));
                                    break;
                                case "inspectionsubject":
                                    inboundQuery = inboundQuery.Where(x => x.InspectionSubject.Contains(param.value));
                                    break;
                                case "inspectiondate":
                                    if (DateTime.TryParse(param.value, out DateTime date))
                                    {
                                        inboundQuery = inboundQuery.Where(x => x.InspectionDate == date);
                                    }
                                    break;
                                // 可以添加更多条件
                            }
                        }
                    }
                }

                // 获取总记录数
                int total = await inboundQuery.CountAsync();

                // 获取分页数据 - 只从到货检验表中获取基础数据
                var inboundDataList = await inboundQuery
                    .OrderByDescending(x => x.CreateDate)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .Select(x => new
                    {
                        x.InspectionOrderID,
                        x.InspectionOrderCode,
                        x.InspectionSubject,
                        x.InspectionDate,
                        x.Inspector,
                        x.Department,
                        x.ContactPhone,
                        x.InspectorRemark,
                        x.PurchaseOrderID,
                        x.CreateDate,
                        x.Creator
                    })
                    .ToListAsync();

                // 获取相关的采购订单信息
                var purchaseOrderIds = inboundDataList.Select(x => x.PurchaseOrderID).ToList();
                var orderDataList = await _purchaseOrderRepository
                    .FindAsIQueryable(x => purchaseOrderIds.Contains(x.purchase_orderid))
                    .Select(x => new
                    {
                        PurchaseOrderID = x.purchase_orderid,
                        OrderNo = x.order_no
                    })
                    .ToListAsync();

                // 获取相关的检验明细信息（用于汇总）
                var inspectionIds = inboundDataList.Select(x => x.InspectionOrderID).ToList();
                var detailSummaryList = await _inspectionDetailRepository
                    .FindAsIQueryable(x => x.InspectionOrderID.HasValue && inspectionIds.Contains(x.InspectionOrderID.Value))
                    .GroupBy(x => x.InspectionOrderID)
                    .Select(g => new
                    {
                        InspectionOrderID = g.Key,
                        TotalReceived = g.Sum(x => x.ReceivedQuantity ?? 0),
                        TotalInspected = g.Sum(x => x.InspectedQuantity ?? 0),
                        TotalQualified = g.Sum(x => x.QualifiedQuantity ?? 0),
                        TotalReturned = g.Sum(x => x.ReturnQuantity ?? 0),
                        TotalStockable = g.Sum(x => x.StockableQuantity ?? 0)
                    })
                    .ToListAsync();

                // 手动关联数据
                var result = inboundDataList.Select(inbound =>
                {
                    // 查找对应的采购订单
                    var order = orderDataList.FirstOrDefault(o => o.PurchaseOrderID == inbound.PurchaseOrderID);
                    
                    // 查找对应的明细汇总
                    var summary = detailSummaryList.FirstOrDefault(s => s.InspectionOrderID == inbound.InspectionOrderID);

                    return new
                    {
                        inbound.InspectionOrderID,
                        inbound.InspectionOrderCode,
                        inbound.InspectionSubject,
                        inbound.InspectionDate,
                        inbound.Inspector,
                        inbound.Department,
                        inbound.ContactPhone,
                        inbound.InspectorRemark,
                        inbound.PurchaseOrderID,
                        order_no = order != null ? order.OrderNo : string.Empty,
                        inbound.CreateDate,
                        inbound.Creator,
                        
                        // 明细数据和汇总信息
                        TotalReceived = summary != null ? summary.TotalReceived : 0,
                        TotalInspected = summary != null ? summary.TotalInspected : 0,
                        TotalQualified = summary != null ? summary.TotalQualified : 0,
                        TotalReturned = summary != null ? summary.TotalReturned : 0,
                        TotalStockable = summary != null ? summary.TotalStockable : 0
                    };
                }).ToList();

                // 返回结果
                return new PageGridData<object>
                {
                    status = 0, // 通常0表示成功
                    msg = "OK",
                    total = total,
                    rows = result.Cast<object>().ToList(),
                    summary = null,
                    extra = null
                };
            }
            catch (Exception ex)
            {
                // 记录异常并返回错误信息
                Console.WriteLine($"获取到货检验单数据异常: {ex.Message}");
                return new PageGridData<object>
                {
                    status = 1, // 1表示失败
                    msg = $"获取数据失败: {ex.Message}",
                    total = 0,
                    rows = new List<object>(),
                    summary = null,
                    extra = null
                };
            }
        }



        /// <summary>
        /// 获取检验单详情
        /// </summary>
        /// <param name="inspectionOrderId">检验单ID</param>
        /// <returns>检验单详细信息</returns>
        public async Task<object> GetInspectionOrderDetail(Guid inspectionOrderId)
        {
            try
            {
                // 获取检验单基本信息
                var inspectionOrder = await repository.FindAsIQueryable(x => x.InspectionOrderID == inspectionOrderId)
                    .FirstOrDefaultAsync();

                if (inspectionOrder == null)
                {
                    return new { status = false, message = "未找到指定的检验单" };
                }

                // 获取关联的采购单信息
                var purchaseOrder = await _purchaseOrderRepository.FindAsIQueryable(x => x.purchase_orderid == inspectionOrder.PurchaseOrderID)
                    .Select(p => new
                    {
                        p.purchase_orderid,
                        p.order_no,
                        p.order_title,
                        p.purchase_date,
                        p.status,
                        p.purchase_supplierid,
                        p.purchase_employeeid
                    })
                    .FirstOrDefaultAsync();

                // 获取供应商信息
                var supplier = purchaseOrder != null ?
                    await _purchaseOrderSupplierRepository.FindAsIQueryable(x => x.purchase_supplierid == purchaseOrder.purchase_supplierid)
                    .Select(s => new
                    {
                        s.supplier_name,
                        s.contact_person,
                        s.contact_phone
                    })
                    .FirstOrDefaultAsync() : null;

                // 获取采购人员信息
                var employee = purchaseOrder != null ?
                    await _purchaseEmployeeRepository.FindAsIQueryable(x => x.purchase_employeeid == purchaseOrder.purchase_employeeid)
                    .Select(e => new
                    {
                        e.purchase_person,
                        e.purchase_dept,
                        e.contact_method
                    })
                    .FirstOrDefaultAsync() : null;

                // 获取附件信息
                var attachment = await _attachmentRepository.FindAsIQueryable(x => x.InspectionOrderID == inspectionOrderId)
                    .Select(a => new
                    {
                        a.AttachmentID,
                        a.AttachmentFileName,
                        a.AttachmentFileSize,
                        a.AttachmentFilePath,
                        a.UploadDate
                    })
                    .FirstOrDefaultAsync();

                // 构建返回结果
                return new
                {
                    status = true,
                    data = new
                    {
                        // 检验单基本信息
                        inspectionOrder.InspectionOrderID,
                        inspectionOrder.InspectionOrderCode,
                        inspectionOrder.InspectionSubject,
                        inspectionOrder.InspectionDate,
                        inspectionOrder.Inspector,
                        inspectionOrder.Department,
                        inspectionOrder.ContactPhone,
                        inspectionOrder.InspectorRemark,
                        inspectionOrder.CreateDate,
                        inspectionOrder.Creator,

                        // 采购单信息
                        PurchaseOrder = purchaseOrder != null ? new
                        {
                            purchaseOrder.purchase_orderid,
                            purchaseOrder.order_no,
                            purchaseOrder.order_title,
                            purchaseOrder.purchase_date,
                            purchaseOrder.status
                        } : null,

                        // 供应商信息
                        Supplier = supplier,

                        // 采购人员信息
                        Employee = employee,

                        // 附件信息
                        Attachment = attachment
                    }
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取检验单详情异常: {ex.Message}");
                return new { status = false, message = $"获取检验单详情失败: {ex.Message}" };
            }
        }

        /// <summary>
        /// 获取检验明细列表
        /// </summary>
        /// <param name="inspectionOrderId">检验单ID</param>
        /// <returns>检验明细列表</returns>
        public async Task<object> GetInspectionDetails(Guid inspectionOrderId)
        {
            try
            {
                // 添加日志输出，帮助调试
                Console.WriteLine($"获取检验明细，检验单ID: {inspectionOrderId}");

                // 先查询是否有匹配的记录
                var count = await _inspectionDetailRepository.FindAsIQueryable(x =>
                    x.InspectionOrderID == inspectionOrderId ||
                    (x.InspectionOrderID.HasValue && x.InspectionOrderID.Value == inspectionOrderId))
                    .CountAsync();

                Console.WriteLine($"找到匹配记录数: {count}");

                // 修改查询条件，处理可空字段情况
                var details = await _inspectionDetailRepository.FindAsIQueryable(x =>
                    x.InspectionOrderID == inspectionOrderId ||
                    (x.InspectionOrderID.HasValue && x.InspectionOrderID.Value == inspectionOrderId))
                    .Select(d => new
                    {
                        d.InspectionDetailID,
                        d.MaterialId,
                        d.MaterialCode,
                        d.MaterialName,
                        d.MaterialType,
                        d.MaterialModel,
                        d.UnitName,
                        d.Brand,
                        d.PurchaseUnitPrice,
                        d.SalePrice,
                        d.ReceivedQuantity,
                        d.InspectedQuantity,
                        d.QualifiedQuantity,
                        d.ReturnQuantity,
                        d.StockableQuantity,
                        d.InspectionType,
                        d.InspectionDetailRemark
                    })
                    .ToListAsync();

                // 输出结果中的字段值，帮助调试
                foreach (var detail in details)
                {
                    Console.WriteLine($"明细ID: {detail.InspectionDetailID}, 物料编码: {detail.MaterialCode}, 物料名称: {detail.MaterialName}");
                }

                // 计算汇总数据
                var summary = new
                {
                    TotalReceived = details.Sum(d => d.ReceivedQuantity ?? 0),
                    TotalInspected = details.Sum(d => d.InspectedQuantity ?? 0),
                    TotalQualified = details.Sum(d => d.QualifiedQuantity ?? 0),
                    TotalReturned = details.Sum(d => d.ReturnQuantity ?? 0),
                    TotalStockable = details.Sum(d => d.StockableQuantity ?? 0)
                };

                return new
                {
                    status = true,
                    data = details,
                    summary = summary
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取检验明细异常: {ex.Message}");
                return new { status = false, message = $"获取检验明细失败: {ex.Message}" };
            }
        }

        /// <summary>
        /// 获取采购单详细信息
        /// </summary>
        /// <param name="purchaseOrderId">采购单ID</param>
        /// <returns>采购单详细信息</returns>
        public async Task<object> GetPurchaseOrderInfo(Guid purchaseOrderId)
        {
            try
            {
                // 获取采购单基本信息
                var purchaseOrder = await _purchaseOrderRepository.FindAsIQueryable(x => x.purchase_orderid == purchaseOrderId)
                    .FirstOrDefaultAsync();

                if (purchaseOrder == null)
                {
                    return new { status = false, message = "未找到指定的采购单" };
                }

                // 获取供应商信息
                var supplier = await _purchaseOrderSupplierRepository.FindAsIQueryable(x => x.purchase_supplierid == purchaseOrder.purchase_supplierid)
                    .Select(s => new
                    {
                        s.supplier_name,
                        s.contact_person,
                        s.contact_phone,
                       
                        
                    })
                    .FirstOrDefaultAsync();

                // 获取采购人员信息
                var employee = await _purchaseEmployeeRepository.FindAsIQueryable(x => x.purchase_employeeid == purchaseOrder.purchase_employeeid)
                    .Select(e => new
                    {
                        e.purchase_person,
                        e.purchase_dept,
                        e.contact_method
                    })
                    .FirstOrDefaultAsync();

                // 返回结果
                return new
                {
                    status = true,
                    data = new
                    {
                        // 采购单信息
                        purchaseOrder.purchase_orderid,
                        purchaseOrder.order_no,
                        purchaseOrder.order_title,
                        purchaseOrder.purchase_date,
               
                        purchaseOrder.related_project,
                        purchaseOrder.status,
                        purchaseOrder.sales_no,
                        purchaseOrder.remark,

                        // 供应商信息
                        Supplier = supplier,

                        // 采购人员信息
                        Employee = employee
                    }
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取采购单信息异常: {ex.Message}");
                return new { status = false, message = $"获取采购单信息失败: {ex.Message}" };
            }
        }

        /// <summary>
        /// 下载附件
        /// </summary>
        /// <param name="attachmentId">附件ID</param>
        /// <returns>附件信息</returns>
        public async Task<object> GetAttachmentInfo(Guid attachmentId)
        {
            try
            {
                // 获取附件信息
                var attachment = await _attachmentRepository.FindAsIQueryable(x => x.AttachmentID == attachmentId)
                    .Select(a => new
                    {
                        a.AttachmentID,
                        a.AttachmentFileName,
                        a.AttachmentFileSize,
                        a.AttachmentFilePath,
                        a.UploadDate
                    })
                    .FirstOrDefaultAsync();

                if (attachment == null)
                {
                    return new { status = false, message = "未找到指定的附件" };
                }

                return new
                {
                    status = true,
                    data = attachment
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取附件信息异常: {ex.Message}");
                return new { status = false, message = $"获取附件信息失败: {ex.Message}" };
            }
        }
        /// <summary>
        /// 根据检验单ID获取附件列表
        /// </summary>
        /// <param name="inspectionOrderId">检验单ID</param>
        /// <returns>附件列表</returns>
        public async Task<object> GetAttachmentsByInspectionId(Guid inspectionOrderId)
        {
            try
            {
                // 获取附件信息
                var attachments = await _attachmentRepository.FindAsIQueryable(x => x.InspectionOrderID == inspectionOrderId)
                    .Select(a => new
                    {
                        a.AttachmentID,
                        a.AttachmentFileName,
                        a.AttachmentFileSize,
                        a.AttachmentFilePath,
                        a.UploadDate
                    })
                    .ToListAsync();

                if (attachments == null || !attachments.Any())
                {
                    return new { status = true, data = new List<object>(), message = "该检验单没有相关附件" };
                }

                return new
                {
                    status = true,
                    data = attachments
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取检验单附件异常: {ex.Message}");
                return new { status = false, message = $"获取检验单附件失败: {ex.Message}" };
            }
        }
        /// <summary>
        /// 获取操作日志
        /// </summary>
        /// <param name="inspectionOrderId">检验单ID</param>
        /// <returns>操作日志列表</returns>
        public async Task<object> GetOperationLogs(Guid inspectionOrderId)
        {
            try
            {
                // 假设有一个操作日志表，这里模拟数据
                // 实际应该连接到你的操作日志表进行查询
                var logs = new List<object>
        {
            new
            {
                LogId = Guid.NewGuid(),
                InspectionOrderID = inspectionOrderId,
                OperationType = "创建",
                OperationTime = DateTime.Now.AddDays(-3),
                Operator = "张三",
                OperationContent = "创建了检验单"
            },
            new
            {
                LogId = Guid.NewGuid(),
                InspectionOrderID = inspectionOrderId,
                OperationType = "修改",
                OperationTime = DateTime.Now.AddDays(-2),
                Operator = "李四",
                OperationContent = "修改了检验明细"
            },
            new
            {
                LogId = Guid.NewGuid(),
                InspectionOrderID = inspectionOrderId,
                OperationType = "审核",
                OperationTime = DateTime.Now.AddDays(-1),
                Operator = "王五",
                OperationContent = "审核通过"
            }
        };

                return new
                {
                    status = true,
                    data = logs
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取操作日志异常: {ex.Message}");
                return new { status = false, message = $"获取操作日志失败: {ex.Message}" };
            }
        }

    }



}
